<template>
  <div class="addMonent-pages">
    <cp-nav-bar left-arrow>
      <template #right>
        <van-button type="danger" size="small" round :disabled="isDisabled" @click="post">
          <van-icon name="plus" color="white" />
          发表</van-button
        >
      </template>
    </cp-nav-bar>
    <div>
      <van-cell-group inset>
        <van-field
          v-model="message"
          rows="2"
          autosize
          type="textarea"
          maxlength="250"
          placeholder="分享生活点滴"
          show-word-limit
        />
      </van-cell-group>
      <van-uploader
        v-model="fileList"
        :multiple="false"
        :max-count="9"
        preview-size="100px"
        style="margin-left: 28px"
        :after-read="afterRead"
        @delete="handleDelete"
      />
    </div>
  </div>
</template>
<script setup lang="ts">
import { createPost } from '@/services/monents'
import type { UploaderFileListItem } from 'vant'
import axios from 'axios'
import { showFailToast, showSuccessToast } from 'vant'
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'

const message = ref('')

const isDisabled = ref(false)
const router = useRouter()

// 定义带url属性的文件列表类型
interface CustomFileItem extends UploaderFileListItem {
  url?: string
}

const fileList = ref<CustomFileItem[]>([])

// 计算属性获取已上传的图片URL数组
const uploadedImages = computed(() =>
  fileList.value
    .filter((item) => item.status !== 'failed' && item.url)
    .map((item) => item.url as string)
)

const afterRead = async (item: CustomFileItem) => {
  item.status = 'uploading'
  const formData = new FormData()
  formData.append('image', item.file!)

  try {
    const response = await axios.post('http://127.0.0.1:3000/chat/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    // 将服务器返回的url保存到文件对象中
    item.url = response.data.data.imagePath
    item.status = 'done'
  } catch {
    item.status = 'failed'
    showFailToast('图片上传失败')
  }
}

// 处理删除事件
const handleDelete = (file: CustomFileItem) => {
  // 自动同步：fileList会自动更新，uploadedImages计算属性也会自动更新
}

const post = async () => {
  if (!message.value.trim()) {
    showFailToast('文章内容不能为空')
    return
  }

  // 使用计算属性中的图片数组
  await createPost(message.value, uploadedImages.value)
  showSuccessToast('发表成功')
  router.push('/moments')
}
</script>
<style lang="scss" scoped>
.addMonent-pages {
  padding-top: 45px;
  height: 100vh;
  box-sizing: border-box;
  background-color: var(--bg-primary);
}
</style>
